package com.xxl.job.kettle.service.exceptionHandler;

import com.xxl.job.kettle.constant.Constant;
import com.xxl.job.kettle.enums.GlobalStatusEnum;
import com.xxl.job.kettle.exception.ExecutorException;
import com.xxl.job.kettle.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 实现功能：
 *
 * @author 作者[zk]
 * @version 1.0.00  2022-11-28 08:55
 */
@Slf4j
@ControllerAdvice
public class ExecutorExceptionHandler {

    //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常，详情继续往下看代码
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        log.debug(message);
        return Result.error(GlobalStatusEnum.FAIL.getCode(), message);
    }

    //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        log.debug(message);
        return Result.error(GlobalStatusEnum.FAIL.getCode(), message);
    }

    //处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        log.debug(message);
        return Result.error(GlobalStatusEnum.FAIL.getCode(), message);
    }

    //自定义异常处理
    @ExceptionHandler(value = ExecutorException.class)
    @ResponseBody
    public Result<?> exception(ExecutorException e){
        log.debug(e.getErrorMsg());
        return Result.error(e.getErrorCode(), e.getErrorMsg());
    }

    //自定义异常处理
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<?> exception(Exception e){
        log.debug(e.getMessage());
        return Result.error(Constant.SC_INTERNAL_SERVER_ERROR_500, e.getMessage());
    }
}
